package com.own.component.common.login.core;

import com.own.component.common.login.user.BaseLoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * UserStatusSpringHook
 *
 * @author chenxueli
 * @date 2022-08-10 15:40:00
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class UserStatusSpringHook implements ApplicationContextAware, ApplicationListener<ApplicationEvent> {

    private static final List<UserStatusHook> USER_STATUS_HOOK_LIST = new ArrayList<>();
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        UserStatusSpringHook.applicationContext = context;
    }

    /**
     * 移出对应用户的信息
     *
     * @param loginUser 登录的用户信息
     */
    public void clear(BaseLoginUser loginUser) {
        USER_STATUS_HOOK_LIST.stream().forEach(item -> item.clear(loginUser));
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            applicationContext.getBeansOfType(UserStatusHook.class).forEach((key, service) -> {
                log.debug("用户信息清理接口===>【{}】完成注册", key);
                USER_STATUS_HOOK_LIST.add(service);
            });
        }
    }

}
